﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SharePoint.Log.Viewer._2010
{
    public partial class frmMain : Form
    {
        private int childFormNumber = 0;

        public frmMain()
        {
            InitializeComponent();
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            Form childForm = new Form();
            childForm.MdiParent = this;
            childForm.Text = "Window " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            RefreshTreeview();
        }

        private void RefreshTreeview()
        {
            Utils utils = new Utils();
            List<KeyValuePair<string, string>> files = utils.GetLOGSFile();
            PopulateLOGSTreeview(files);
        }

        private void PopulateLOGSTreeview(List<KeyValuePair<string, string>> files)
        {
            trvLog.Nodes.RemoveAt(0);
            trvLog.Nodes.Add("SharePoint LOGS Root");
            if (files.Count() > 0)
            {
                foreach (var item in files)
                {
                    trvLog.Nodes[0].Nodes.Add(item.Key, item.Value, 1);
                }
                trvLog.Nodes[0].SelectedImageIndex = 0;
                trvLog.ExpandAll();
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshTreeview();
            RefreshGridview("", false);
        }

        private void trvLog_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string key = e.Node.Name;
            txtPageMem.Text = "0";
            RefreshGridview(key, txtSearch.Text, (DDL_Level.SelectedItem != null)
                ? DDL_Level.SelectedItem.ToString()
                : "");
        }

        private void RefreshGridview(string key, string Search, string LevelFilter)
        {
            try
            {
                tableLayoutPanel1.Controls.Clear();

                Utils utils = new Utils();
                List<Content> contents = utils.GetContent(key);

                if (Search.Trim() != "")
                {
                    contents = (from c in contents
                                where c.Guid.ToString().StartsWith(Search)
                                || c.Message.Contains(Search)
                                select c).ToList();
                }
                if (!string.IsNullOrEmpty(LevelFilter))
                {
                    contents = (from c in contents
                                where c.Level == LevelFilter
                                select c).ToList();
                }

                LogRow logrow;
                BuildPagination(contents.Count());

                int i = 0;
                foreach (var item in contents.OrderByDescending(d => d.Timestamp).Take(10))
                {
                    logrow = new LogRow(item.Timestamp, item.Guid, item.Message, item.Area, item.Level, item.Process, item.TID, item.Category, item.EventID);
                    tableLayoutPanel1.Controls.Add(logrow, 0, i);
                    i++;
                }
                SetDDL_Level(contents);
                frmMain_Resize(null, null);
                tableLayoutPanel1.HorizontalScroll.Visible = false;
                lblTotalLogs.Text = "Logs: " + contents.Count();

                if (contents.Count() > 0)
                    txtSearch.Enabled = true;
                else
                {
                    txtSearch.Text = "";
                    txtSearch.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SharePoint LOG Viewer 2010");
            }
        }

        private void RefreshGridview(string key, bool bPageNext)
        {
            try
            {
                tableLayoutPanel1.Controls.Clear();

                Utils utils = new Utils();
                List<Content> contents = utils.GetContent(key);

                LogRow logrow;
                BuildPagination(contents.Count(), bPageNext);

                var queryPagination = contents.OrderByDescending(d => d.Timestamp)
                    .Skip(int.Parse(txtPageMem.Text) * 10).Take(10);

                int i = 0;
                foreach (var item in queryPagination)
                {
                    logrow = new LogRow(item.Timestamp, item.Guid, item.Message, item.Area, item.Level, item.Process, item.TID, item.Category, item.EventID);
                    tableLayoutPanel1.Controls.Add(logrow, 0, i);
                    i++;
                }
                SetDDL_Level(contents);
                frmMain_Resize(null, null);
                tableLayoutPanel1.HorizontalScroll.Visible = false;
                lblTotalLogs.Text = "Logs: " + contents.Count();

                if (contents.Count() > 0)
                    txtSearch.Enabled = true;
                else
                    txtSearch.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SharePoint LOG Viewer 2010");
            }
        }

        private void RefreshGridview(string key, bool bPageNext, string Search, string LevelFilter)
        {
            try
            {
                tableLayoutPanel1.Controls.Clear();

                Utils utils = new Utils();
                List<Content> contents = utils.GetContent(key);
                if (Search.Trim() != "")
                {
                    contents = (from c in contents
                                where c.Guid.ToString().StartsWith(Search)
                                || c.Message.Contains(Search)
                                select c).ToList();
                }
                if (!string.IsNullOrEmpty(LevelFilter))
                {
                    contents = (from c in contents
                                where c.Level == LevelFilter
                                select c).ToList();
                }

                LogRow logrow;
                BuildPagination(contents.Count(), bPageNext);

                var queryPagination = contents.OrderByDescending(d => d.Timestamp)
                    .Skip(int.Parse(txtPageMem.Text) * 10).Take(10);

                int i = 0;
                foreach (var item in queryPagination)
                {
                    logrow = new LogRow(item.Timestamp, item.Guid, item.Message, item.Area, item.Level, item.Process, item.TID, item.Category, item.EventID);
                    tableLayoutPanel1.Controls.Add(logrow, 0, i);
                    i++;
                }
                SetDDL_Level(contents);
                frmMain_Resize(null, null);
                tableLayoutPanel1.HorizontalScroll.Visible = false;
                lblTotalLogs.Text = "Logs: " + contents.Count();

                if (contents.Count() > 0)
                    txtSearch.Enabled = true;
                else
                {
                    txtSearch.Text = "";
                    txtSearch.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SharePoint LOG Viewer 2010");
            }
        }

        private void SetDDL_Level(List<Content> contents)
        {
            DDL_Level.Items.Clear();

            DDL_Level.Items.Add("");

            if (contents.Count > 0)
            {
                DDL_Level.Visible = true;
                lblLevelFilter.Visible = true;
            }
            else
            {
                DDL_Level.Visible = false;
                lblLevelFilter.Visible = false;
            }

            var groupLevel = contents.GroupBy(l => l.Level);
            foreach (var item in groupLevel)
            {
                DDL_Level.Items.Add(item.Key);
            }
        }

        private void refreshLogContentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (trvLog.SelectedNode != null)
                RefreshGridview(trvLog.SelectedNode.Name, txtSearch.Text, (DDL_Level.SelectedItem != null)
            ? DDL_Level.SelectedItem.ToString()
            : "");
        }

        private void BuildPagination(int count)
        {
            if (count > 0)
            {
                PagePrev.Visible = true;
                PageNext.Visible = true;
                if (count <= 10) PageNext.Enabled = false;
                if (txtPageMem.Text == "" || txtPageMem.Text == "0")
                {
                    PagePrev.Enabled = false;
                }
                else
                {
                    int NextPage = int.Parse(txtPageMem.Text) + 10;
                    if (count >= NextPage)
                        PageNext.Enabled = true;
                    else
                        PageNext.Enabled = false;

                }
            }
            else
            {
                PagePrev.Visible = false;
                PageNext.Visible = false;
            }
        }

        private void BuildPagination(int count, bool bPageNext)
        {
            double total = Math.Ceiling((double)count / (double)10);
            if (total > 0)
            {
                if (total <= 1) PageNext.Enabled = false;
                if (txtPageMem.Text == "" || txtPageMem.Text == "0")
                {
                    PagePrev.Enabled = false;
                }

                int Page = 0;
                if (bPageNext)
                {
                    Page = int.Parse(txtPageMem.Text) + 1;
                }
                else
                {
                    Page = int.Parse(txtPageMem.Text) - 1;
                }

                txtPageMem.Text = Page.ToString();

                if (total > Page + 1)
                    PageNext.Enabled = true;
                else
                    PageNext.Enabled = false;

                if (Page >= 1)
                    PagePrev.Enabled = true;
                else
                    PagePrev.Enabled = false;
            }
            else
            {
                PagePrev.Visible = false;
                PageNext.Visible = false;
            }
        }

        private void PageNext_Click(object sender, EventArgs e)
        {
            if (trvLog.SelectedNode != null)
                RefreshGridview(trvLog.SelectedNode.Name, true, txtSearch.Text, DDL_Level.SelectedItem.ToString());
        }

        private void PagePrev_Click(object sender, EventArgs e)
        {
            if (trvLog.SelectedNode != null)
                RefreshGridview(trvLog.SelectedNode.Name, false, txtSearch.Text, DDL_Level.SelectedItem.ToString());
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (trvLog.SelectedNode != null)
                RefreshGridview(trvLog.SelectedNode.Name, txtSearch.Text, DDL_Level.SelectedItem.ToString());
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmChangeLOGSPath frm = new frmChangeLOGSPath();
            frm.ShowDialog(this);

            RefreshTreeview();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout frm = new frmAbout();
            frm.ShowDialog(this);
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (tableLayoutPanel1.Controls.Count > 0)
            {
                foreach (var item in tableLayoutPanel1.Controls)
                {
                    if (item is LogRow)
                    {
                        LogRow logrow = (LogRow)item;
                        logrow.Width = tableLayoutPanel1.Width - 10;
                        Control c = logrow.Controls.Find("lblMessage", true).FirstOrDefault();
                        c.Width = logrow.Width - 10;
                    }
                }
            }
        }

        private void DDL_Level_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (trvLog.SelectedNode != null)
                RefreshGridview(trvLog.SelectedNode.Name, txtSearch.Text, DDL_Level.SelectedItem.ToString());
        }
    }
}
